package com.raowb.common.base.services.impl;

import java.util.Collection;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.common.utils.SecurityUtils;

import com.raowb.common.base.entitys.BaseEntity;
import com.raowb.common.base.services.BaseService;

/**
 * 
 * @Description:
 * @author: raowb
 * @date 2018年8月6日
 */
public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends BaseIDServiceImpl<M, T>
		implements BaseService<T> {
	
	@Override
	public boolean save(T entity) {
		prepareSave(entity);
		return super.save(entity);
	}

	@Override
	public boolean saveBatch(Collection<T> entityList, int batchSize) {
		prepareSaveBatch(entityList);
		return super.saveBatch(entityList, batchSize);
	}

	@Override
	public boolean update(T entity) {
		prepareUpdate(entity);
		return super.update(entity);
	}

	@Override
	public boolean updateBatch(Collection<T> entityList, int batchSize) {
		prepareUpdateBatch(entityList);
		return super.updateBatch(entityList, batchSize);
	}

	@Override
	public boolean saveOrUpdate(T entity) {
		if (entity.getId() == null) {
			return save(entity);
		} else {
			return update(entity);
		}
	}

	@Override
	public boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize) {
		for (T entity : entityList) {
			if (entity.getId() == null) {
				prepareSave(entity);
			} else {
				prepareUpdate(entity);
			}
		}
		return super.saveOrUpdateBatch(entityList,batchSize);
	}

	/**
	 * 
	* @Title: prepareUpdate
	* @Description: 更新或新增前操作
	* @param entity    设定文件
	* @return void    返回类型
	* @throws
	 */
	protected void prepareUpdate(T entity) {
		entity.setUpdateTime(new Date());
		entity.setUpdaterId(SecurityUtils.getUserId());
		entity.setUpdaterName(SecurityUtils.getUsername());
	}

	protected void prepareSave(T entity) {
		prepareUpdate(entity);
		entity.setCreateTime(entity.getUpdateTime());
		entity.setCreaterId(entity.getUpdaterId());
		entity.setCreaterName(entity.getUpdaterName());
	}

	protected void prepareUpdateBatch(Collection<T> entityList) {
		for (T entity : entityList) {
			prepareUpdate(entity);
		}
	}

	protected void prepareSaveBatch(Collection<T> entityList) {
		for (T entity : entityList) {
			prepareSave(entity);
		}
	}

}
